package com.example.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class Activity1 extends AppCompatActivity {

    private static final String TAG = "Activity1";

    // 得到Service就可以调用Service里的方法了，如果要Service调用Activity方法，可以用回调
    private MyService1 myService1 = null;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        // 绑定时，通过IBinder得到Service
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if(service instanceof MyService1.MyBind) {
                myService1 = ((MyService1.MyBind) service).getService();
                Log.i(TAG, "绑定");
            }
        }
        // 解绑
        @Override
        public void onServiceDisconnected(ComponentName name) {
            myService1 = null;
            Log.i(TAG, "解绑");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_1);

        // 启动服务
        findViewById(R.id.button_start).setOnClickListener(v -> {
            startService(new Intent(this, MyService1.class));
        });
        // 停止服务
        findViewById(R.id.button_stop).setOnClickListener(v -> {
            stopService(new Intent(this, MyService1.class));
        });
        // 绑定服务
        findViewById(R.id.button_bind).setOnClickListener(v -> {
            bindService(new Intent(this, MyService1.class), serviceConnection, Context.BIND_AUTO_CREATE);
        });
        // 解绑服务器
        findViewById(R.id.button_unbind).setOnClickListener(v -> {
            unbindService(serviceConnection);
        });
        // 调用service方法
        findViewById(R.id.button_serviceFunc).setOnClickListener(v -> {
            if (myService1 != null) {
                myService1.xxx();
            }
        });

    }
}